package com.woniuxy.common.utils;


import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;

import com.woniuxy.common.dto.OwnerDto;
import com.woniuxy.common.dto.WcnUserDto;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.alibaba.nacos.api.common.Constants.TOKEN;
import static com.woniuxy.common.constant.FinanceConstant.User.USER;


public class UserUtil {
    public static WcnUserDto getUser(HttpServletRequest request){
        String token = request.getHeader(TOKEN);
        return getUser(token);


    }

    private static WcnUserDto getUser(String token) {
        Object payload = JWTUtil.parseToken(token).getPayload(USER);
        return JSONObject.parseObject(String.valueOf(payload), WcnUserDto.class);
    }

    public static WcnUserDto getUser(ServerHttpRequest request){
        String token = request.getHeaders().getFirst(TOKEN);
        return getUser(token);

    }
    public static String getToken() {
        // 获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 从Authorization头中获取Token
        String token = request.getHeader("Authorization");

        // 处理Bearer前缀（如果有）
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 截取"Bearer "之后的部分
        }
        return token;
    }

    // 解析Token获取用户信息
    public static OwnerDto getUser1(String token) {

        Object payload = JWTUtil.parseToken(token).getPayload(USER);
        return JSONObject.parseObject(String.valueOf(payload), OwnerDto.class);
        // ...
    }

    public static WcnUserDto getUser2(String token) {

        Object payload = JWTUtil.parseToken(token).getPayload(USER);
        return JSONObject.parseObject(String.valueOf(payload), WcnUserDto.class);
        // ...
    }


}
